#ifndef __CDS__LIST__H__
#define __CDS__LIST__H__
#include "cds_common.h"
#ifdef __cplusplus
extern "C" {
#endif

//链表
typedef struct list_head{
   struct list_head * next, *prev;
} list_head_t;

//链表节点初始值
#define LIST_HEAD_INIT(name) {&(name),&(name)}

//定义一个链表节点
#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

//初始化链表节点指针
#define INIT_LIST_HEAD(ptr) do{\
    (ptr)->next = (ptr); (ptr)->prev = (ptr); \
}while(0)

//取当前entry的数据结构指针
#define list_entry(ptr, type, member) \
    container_of(ptr,type,member)

//循环遍历链表
#define list_for_each(pos, head) \
    for( pos = (head)->next; pos != (head); pos = pos->next )

//获取下一个节点
#define list_next(head) \
    head->next

//获取链表的首节点
#define list_first(head) \
    list_next(head)

//获取上一个节点
#define list_prev(head) \
    head->prev

//获取链表尾节点
#define list_last(head) \
    list_prev(head)

//将新节点new插入到prev和next之间
static inline void __list_add(struct list_head* new,
    struct list_head * prev,
    struct list_head * next ){
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

//尾部插入
static inline void list_add(struct list_head * new, 
    struct list_head * head ){
    __list_add(new, head->prev,head);
}

//头部插入
static inline void list_add_head(struct list_head * new, 
    struct list_head * head ){
    __list_add(new, head,head->next);
}

static inline void __list_del(struct list_head * prev,
    struct list_head * next ){
    next->prev = prev;
    prev->next = next;
}

//删除节点entry
static inline void list_del(struct list_head * entry ){
    __list_del(entry->prev, entry->next);
}

//删除头部节点并返回
static inline struct list_head * list_del_first(struct list_head * head ){
   struct list_head * ret = list_first(head);
   list_del(ret);
   return ret;
}

//删除尾部节点并返回
static inline struct list_head * list_del_last(struct list_head * head ){
    struct list_head * ret = list_last(head);
    list_del(ret);
    return ret;
}

//判断链表是否为空
static inline int list_is_empty(struct list_head * head ){
    return head==head->next;
}

//清空链表
void list_clear(struct list_head * head );

#ifdef __cplusplus
}
#endif
#endif // __CDS__LIST__H__
